﻿using Microsoft.EntityFrameworkCore;
using StudentInfoSystem.Core.Models;

namespace StudentInfoSystem.Core.Data.DbContexts
{
    public class AppDbContext : DbContext
    {
        private string v;

        public AppDbContext(string v)
        {
            this.v = v;
        }

        // 数据库表映射
        public DbSet<Student> Students { get; set; }

        // 配置数据库连接
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // 使用SQLite数据库，文件名为students.db
            optionsBuilder.UseSqlite("Data Source=students.db");

            // 添加并发冲突处理
            optionsBuilder.EnableThreadSafetyChecks(false);

            // 启用详细日志记录（开发环境）
#if DEBUG
            optionsBuilder.EnableSensitiveDataLogging();
            optionsBuilder.LogTo(Console.WriteLine);
#endif
        }

        // 配置数据模型
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 学生实体配置
            modelBuilder.Entity<Student>(entity =>
            {
                // 主键设置
                entity.HasKey(s => s.Id);

                // 字段约束
                entity.Property(s => s.Id)
                    .HasMaxLength(8)
                    .IsRequired();

                entity.Property(s => s.Name)
                    .HasMaxLength(50)
                    .IsRequired();

                entity.Property(s => s.College)
                    .HasMaxLength(100);

                entity.Property(s => s.Department)
                    .HasMaxLength(100);

                entity.Property(s => s.Class)
                    .HasMaxLength(50);

                entity.Property(s => s.Dormitory)
                    .HasMaxLength(50);

                entity.Property(s => s.Hometown)
                    .HasMaxLength(100);

                entity.Property(s => s.Phone)
                    .HasMaxLength(20);

                // 添加索引
                entity.HasIndex(s => s.Id).IsUnique();
                entity.HasIndex(s => s.Name);
                entity.HasIndex(s => s.College);
            });
        }

        // 重写保存方法，添加自定义逻辑
        public override int SaveChanges()
        {
            AddTimestamps();
            return base.SaveChanges();
        }

        private void AddTimestamps()
        {
            var entities = ChangeTracker.Entries()
                .Where(x => x.Entity is BaseEntity &&
                           (x.State == EntityState.Added || x.State == EntityState.Modified));

            foreach (var entity in entities)
            {
                var now = DateTime.UtcNow;

                if (entity.State == EntityState.Added)
                {
                    ((BaseEntity)entity.Entity).CreatedAt = now;
                }

                ((BaseEntity)entity.Entity).UpdatedAt = now;
            }
        }
    }

    // 基础实体类（可选）
    public abstract class BaseEntity
    {
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
}